%% Extract estimates for RCT2Scale grouping 2

% Load the group data
groupData = readtable('../Data/RCT2scale_grouping2.xlsx');
group_ids = groupData.id;
group_labels = groupData.group;

% Load the main dataset
mainData = readtable('../Data/NudgeUnits_nopub.xlsx');

% Extract relevant columns
ids = mainData.id;
treatmentEffects = mainData.treatmenteffect;
SEs = mainData.SE;
SampleSizes = mainData.trialN;

% Determine number of groups
unique_groups = unique(group_labels);
num_groups = length(unique_groups);

% Initialize matrices to hold estimates and SEs
Estimates = nan(num_groups, 3);
SE_matrix = nan(num_groups, 3);
SampleSize_matrix = nan(num_groups, 3);

% Populate matrices by group
for i = 1:num_groups
    current_group = unique_groups(i);
    % Find IDs in the current group
    current_ids = group_ids(group_labels == current_group);
    
    % For each ID, find its corresponding treatment effect and SE
    for j = 1:length(current_ids)
        idx = find(ids == current_ids(j));
        if ~isempty(idx)
            Estimates(i, j) = treatmentEffects(idx);
            SE_matrix(i, j) = SEs(idx);
            SampleSize_matrix(i, j) = SampleSizes(idx);
        else
            warning('ID %d not found in main data.', current_ids(j));
        end
    end
end

% Create tables to export
Estimates_table = array2table(Estimates, ...
    'VariableNames', {'Study1', 'Study2', 'Study3'});
SE_table = array2table(SE_matrix, ...
    'VariableNames', {'Study1', 'Study2', 'Study3'});
SampleSize_table = array2table(SampleSize_matrix, ...
    'VariableNames', {'Study1', 'Study2', 'Study3'});

% Write tables to Excel file
output_filename = '../Data/RCT2scale_data2.xlsx';
writetable(Estimates_table, output_filename, 'Sheet', 'Estimates');
writetable(SE_table, output_filename, 'Sheet', 'SE');
writetable(SampleSize_table, output_filename, 'Sheet', 'Sample Size');
